<!-- MathJax.vue -->
<template>
  <div ref="mathContainer" v-html="compiledFormula"></div>
</template>

<script>
import { mathjax } from 'mathjax-full/js/mathjax'
import { TeX } from 'mathjax-full/js/input/tex'
import { SVG } from 'mathjax-full/js/output/svg'
import { liteAdaptor } from 'mathjax-full/js/adaptors/liteAdaptor'
import { RegisterHTMLHandler } from 'mathjax-full/js/handlers/html'

export default {
  name: 'MathJax',
  props: {
    formula: {
      type: String,
      required: true
    },
    inline: {
      type: Boolean,
      default: false
    }
  },
  computed: {
    compiledFormula() {
      return this.renderMath(this.formula, this.inline)
    }
  },
  methods: {
    renderMath(formula, inline = false) {
      try {
        const adaptor = liteAdaptor()
        RegisterHTMLHandler(adaptor)

        const tex = new TeX({ packages: ['base', 'ams'] })
        const svg = new SVG({ fontCache: 'none' })
        const html = mathjax.document('', { InputJax: tex, OutputJax: svg })

        const node = html.convert(formula, {
          display: !inline,
          em: 16,
          ex: 8,
          containerWidth: 800
        })

        return adaptor.outerHTML(node)
      } catch (error) {
        console.error('MathJax渲染错误:', error)
        return `<span style="color: red;">公式渲染错误: ${formula}</span>`
      }
    }
  },
  watch: {
    formula() {
      this.$nextTick(() => {
        // 公式更新后重新渲染
      })
    }
  }
}
</script>
